﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MacomberMapSystem.Common.Serialization;
using MacomberMapSystem.Common.Database;
using System.Windows.Forms;
using MacomberMapSystem.Common.CIM;
using MacomberMapSystem.Common.User_Interfaces.One_Lines;

namespace MacomberMapSystem.Common.User_Interfaces.Database
{
    /// <summary>
    /// (C) 2013, Michael E. Legatt, Ph.D., Electric Reliability Council of Texas, Inc.
    /// This class holds information on one-lines assigned to a particular user
    /// </summary>
    public class ctlOneLineAssignments: ListView
    {
        #region Variable declarations
        /// <summary>The data repository associated with the user information</summary>
        private MM_Repository Repository;

        /// <summary>Our assignment sorter</summary>
        private MM_Database_Assignment_Sorter Sorter;

        /// <summary>Our collection of assignments</summary>
        public List<MM_Database_Assignment> Assignments = new List<MM_Database_Assignment>();

        /// <summary>The user selected for whom assignments are viewed</summary>
        public MM_Database_User SelectedUser;

        /// <summary>Our one-line editor</summary>
        public ctlOneLineEditor OneLineEditor = null;
        #endregion

        #region Initialization
        /// <summary>
        /// Initialize our one-line assignment viewer
        /// </summary>
        public ctlOneLineAssignments()
        {
            this.Activation = System.Windows.Forms.ItemActivation.OneClick;
            this.Columns.Add("Model");
            this.Columns.Add("Element");
            this.Columns.Add("Assigned on");
            this.Columns.Add("Errors");
            this.Columns.Add("Warnings");                                  
            this.FullRowSelect = true;
            this.Groups.Add("Errors", "Errors");
            this.Groups.Add("Warnings", "Warnings");            
            this.HideSelection = false;
            this.ShowItemToolTips = true;
            this.Sorter = new MM_Database_Assignment_Sorter(this.Columns[0], true);
            this.ColumnClick += new ColumnClickEventHandler(ctlOneLineAssignments_ColumnClick);
            this.SelectedIndexChanged += new EventHandler(ctlOneLineAssignments_SelectedIndexChanged);
            this.MouseDoubleClick += new MouseEventHandler(ctlOneLineAssignments_MouseDoubleClick);
        }


        /// <summary>
        /// Handle a mouse double click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlOneLineAssignments_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo hti = HitTest(e.Location);
            if (hti.Item != null && hti.Item.Tag is MM_Database_Assignment)
            {
                MM_Database_Assignment Assignment = hti.Item.Tag as MM_Database_Assignment;
                if (Assignment.Model.State != MM_Database_Model.enumModelState.Completed)
                    if (!Assignment.Model.EnsureOpened())
                        return;
                MM_Database_OneLine OneLine = Repository.Db.LoadOneLine(Assignment.OneLine, Repository);
                new frmOneLineEditor(OneLine, Assignment.Model, Assignment.Model.FromRdfID(OneLine.rdfID), Assignment, Repository).Show();
            }

        }

        

        /// <summary>
        /// Handle the selection change in our control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ctlOneLineAssignments_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (OneLineEditor == null)
                return;
            else if (SelectedItems.Count != 1)
                OneLineEditor.ClearOneLine();
            else
                try
                {
                    //First, make sure our model is open
                    MM_Database_Assignment ActiveAssignment = SelectedItems[0].Tag as MM_Database_Assignment;
                    MM_Database_OneLine ActiveOneLine = ActiveAssignment.GetOneLine(Repository);
                    MM_Database_Model ActiveModel = ActiveAssignment.Model;

                    if (!ActiveModel.EnsureOpened())
                    {
                        OneLineEditor.ClearOneLine();
                        return;
                    }

                    CIM_Element BaseElement = ActiveModel.FromRdfID(ActiveOneLine.rdfID);

                    try
                    {
                        OneLineEditor.LoadOneLine(ActiveOneLine, ActiveModel, BaseElement, ActiveAssignment, Repository);
                    }
                    catch
                    { }
                    OneLineEditor.ApplyValidationResults(ActiveAssignment.Notes);
                    MessageBox.Show(ActiveAssignment.Notes, BaseElement.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error opening one-line: " + ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
        }

        /// <summary>
        /// Resort our list of assignments
        /// </summary>
        public void ReSort()
        {
            Assignments.Sort(Sorter);

            List<ListViewItem> ToAdd = new List<ListViewItem>();
            Sorting = SortOrder.None;
            Items.Clear();
            foreach (MM_Database_Assignment Assignemnt in Assignments)
            {
                ListViewItem lvI = new ListViewItem();
                lvI.Text = Assignemnt.Model.Name;
                lvI.Name = "a" + Assignemnt.ID.ToString();
                lvI.ImageIndex = 0;
                //lvOneLines.Items.Add("a" + Assignemnt.ID.ToString(), Assignemnt.Model.Name, 0);
                lvI.Tag = Assignemnt;
                lvI.SubItems.Add(Assignemnt.OneLineName);
                lvI.SubItems.Add(Assignemnt.AssignedOn.ToString());
                lvI.SubItems.Add(Assignemnt.Errors.ToString("#,##0"));
                lvI.SubItems.Add(Assignemnt.Warnings.ToString("#,##0"));
                lvI.ToolTipText = Assignemnt.Notes;
                if (Assignemnt.Errors > 0)
                    lvI.Group = Groups["Errors"];
                else
                    lvI.Group = Groups["Warnings"];
                Items.Add(lvI);
                ToAdd.Add(lvI);
            }
        }

        /// <summary>
        /// Handle a column click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlOneLineAssignments_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (Sorter.SortCol == Columns[e.Column])
                Sorter.Ascending ^= true;
            else
            {
                Sorter.SortCol = Columns[e.Column];
                Sorter.Ascending = true;
            }
            ReSort();
        }


        /// <summary>
        /// Initialize our list view
        /// </summary>
        /// <param name="Repository"></param>
        /// <param name="SelectedUser"></param>
        public void Initialize(MM_Repository Repository, MM_Database_User SelectedUser)
        {
            this.Repository = Repository;
            Assignments.Clear();
            if (SelectedUser != null)
                foreach (MM_Database_Assignment Assignment in Repository.Db.LoadActiveOneLineAssignments(Repository, SelectedUser).Values)
                    Assignments.Add(Assignment);
            ReSort();
            if (OneLineEditor != null)
                OneLineEditor.ClearOneLine();
            AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }
        #endregion



    }
}
